package com.example.hello.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

  @Value("${spring.datasource.url}")
  private String url;

  @Value("${spring.datasource.username}")
  private String username;

  @Value("${spring.datasource.password}")
  private String password;

  @Value("${spring.datasource.driver-class-name}")
  private String driverClassName;

  @Bean
  @Primary
  public DataSource dataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);

    // 连接池配置
    dataSource.setMinimumIdle(5);
    dataSource.setMaximumPoolSize(15);
    dataSource.setAutoCommit(true);
    dataSource.setIdleTimeout(30000);
    dataSource.setPoolName("RoadTripHikariCP");
    dataSource.setMaxLifetime(1800000);
    dataSource.setConnectionTimeout(30000);
    dataSource.setConnectionTestQuery("SELECT 1");

    return dataSource;
  }
}